package org.mobiletrain.android43_activeandroid;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Delete;
import com.activeandroid.query.Select;
import com.activeandroid.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.listView_main)
    ListView listView_main;
    @Bind(R.id.textView_empty)
    TextView textView_empty;
    private Context mContext = this;
    private EditText editText_dialog_name;
    private EditText editText_dialog_sex;
    private EditText editText_dialog_age;
    private MyListViewAdapter adapter = null;
    private List<Student> totalList = new ArrayList<Student>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private List<Student> selectData() {
        Select select = new Select();
        List<Student> result = select.from(Student.class).orderBy("id desc").execute();
        return result;
    }

    private void initView() {
        ButterKnife.bind(this);
        // 给数据源赋值
        totalList = selectData();
        adapter = new MyListViewAdapter(mContext, totalList);
        listView_main.setAdapter(adapter);
        listView_main.setEmptyView(textView_empty);
        // 给ListView注册上下文菜单
        registerForContextMenu(listView_main);
    }

    private void initDialogView(View view) {
        editText_dialog_name = (EditText) view.findViewById(R.id.editText_dialog_name);
        editText_dialog_sex = (EditText) view.findViewById(R.id.editText_dialog_sex);
        editText_dialog_age = (EditText) view.findViewById(R.id.editText_dialog_age);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        // 通过actionView的id获取MenuItem
        MenuItem item = menu.findItem(R.id.action_searchview);
        // 通过MenuItem初始化ActionView
        SearchView searchView = (SearchView) item.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Select select = new Select();
                List<Student> result = select.from(Student.class).where("name like ?", "%" + newText + "%").orderBy("id desc").execute();
                //刷新适配器
                adapter.reloadListView(result, true);
                return false;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_insert:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);

                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("添加数据");
                View view = getLayoutInflater().inflate(R.layout.dialog_execdata, null);
                //初始化对话框上的控件
                initDialogView(view);

                builder.setView(view);
                builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (!TextUtils.isEmpty(editText_dialog_age.getText()) && !TextUtils.isEmpty(editText_dialog_name.getText()) && !TextUtils.isEmpty(editText_dialog_sex.getText())) {
                            String name = editText_dialog_name.getText().toString();
                            String age = editText_dialog_age.getText().toString();
                            String sex = editText_dialog_sex.getText().toString();
                            // 创建Student对象
                            Student student = new Student();
                            student.setName(name);
                            if (isNumeric(age)) {
                                student.setAge(Integer.parseInt(age));
                            } else {
                                student.setAge(0);
                            }
                            student.setSex(sex);
                            student.setGrade(name);
                            Long id = student.save();
                            Toast.makeText(mContext, "添加Ok！id=" + id, Toast.LENGTH_SHORT).show();

                            // 重新加载ListView
                            adapter.reloadListView(selectData(), true);
                        } else {
                            Toast.makeText(mContext, "填写项不可以为空！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();

                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        menu.setHeaderIcon(R.mipmap.ic_launcher);
        // 从数据源中取出name，作为上下文菜单的title
        menu.setHeaderTitle(totalList.get(info.position).getName());
        getMenuInflater().inflate(R.menu.contextmenu_listview, menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ContextMenu.ContextMenuInfo menuInfo = item.getMenuInfo();
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        final long _id = totalList.get(info.position).getId();
        final Student student = totalList.get(info.position);

        switch (item.getItemId()) {
            case R.id.action_delete:
                //方法1：
                //student.delete();

                //方法2：
                Delete delete = new Delete();
                delete.from(Student.class).where("id =?", _id).execute();

                // 重新加载ListView
                adapter.reloadListView(selectData(), true);
                break;

            case R.id.action_update:
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("修改数据");
                View view = getLayoutInflater().inflate(R.layout.dialog_execdata, null);
                //初始化对话框上的控件
                initDialogView(view);

                // 查询长按所对应的这条数据，给相应的控件赋值
                editText_dialog_name.setText(student.getName());
                editText_dialog_age.setText(student.getAge() + "");
                editText_dialog_sex.setText(student.getSex());

                builder.setView(view);
                builder.setPositiveButton("修改", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = editText_dialog_name.getText() + "";
                        String age = editText_dialog_age.getText() + "";
                        String sex = editText_dialog_sex.getText() + "";
                        //Log.i("tag", "--->name=" + name +",age = " + age + ", sex = " + sex + ",id" + _id);

                        // 方法1：修改Student对象中的数据
                        /*student.setName(name);
                        student.setAge(Integer.parseInt(age));
                        student.setSex(sex);
                        student.save();*/

                        //方法2：更新数据
                        Update update = new Update(Student.class);
                        update.set("name=? , age=? , sex=?", name , age , sex).where("id=?", _id).execute();

                        // 重新加载ListView
                        adapter.reloadListView(selectData(), true);
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
                break;
        }
        return super.onContextItemSelected(item);
    }


    static class DialogViewHolder {
        @Bind(R.id.editText_dialog_name)
        EditText editText_dialog_name;
        @Bind(R.id.editText_dialog_sex)
        EditText editText_dialog_sex;
        @Bind(R.id.editText_dialog_age)
        EditText editText_dialog_age;

        DialogViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }


    public static boolean isNumeric(String str){
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
}

